
import bitarray
import binascii

class Queue:
  def __init__(self,size,value):
    self.queue = [value]*size
    self.size = size
    
  def all_packets_received(self):
    try:
      packet_id = (i for i,v in enumerate(self.queue) if not v).next()
    except StopIteration:
      packet_id = None
    if not packet_id:
      return True
      
  def __setitem__(self,index,item):
    self.queue[index] = item
    
  def __str__(self):
    out = '|'
    for item in self.queue:
      if item:
        out += '.'
      else:
        out += ' '
    out += '|'
    
    return binascii.b2a_hex(self.pack())
    return out
  
  def get_inverse(self):
    invert_queue = Queue(self.size,0)
    invert_queue.queue = [not item for item in self.queue]
    return invert_queue
  
  def pack(self):
    bits = bitarray.bitarray()
    bits.extend(self.queue)
    return bits.tobytes()
  
  def unpack(self,bytestr):
    bits = bitarray.bitarray()
    bits.frombytes(bytestr)
    self.queue = bits.tolist()[:self.size]
    
  def empty(self):
    return self.next_id() == None
  
  def next_id(self):
    try:
      packet_id = (i for i,v in enumerate(self.queue) if v).next()
    except StopIteration:
      packet_id = None
    return packet_id